import { getToken, setToken, removeToken, setTokenTime } from '@/utils/auth'
import { login, getInfo, getUserDetail } from '@/api/user'
import { resetRouter, constantRoutes } from '@/router'

export default {
  namespaced: true,
  // 状态
  state: {
    token: getToken(),
    userInfo: {},
    routerMenus: []
  },
  // 修改状态
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    setUserInfo(state, info) {
      state.userInfo = { ...info }
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    },
    setMenus(state, payload) {
      state.routerMenus = [...constantRoutes, ...payload]
    }
  },
  // 执行异步
  actions: {
    async login({ commit }, userInfo) {
      const token = await login(userInfo)
      commit('setToken', token)
      // 存储登录时间戳
      setTokenTime()
    },
    // 登录获取用户信息
    async getUserInfo({ commit }) {
      const result = await getInfo()
      // 获取用户详细信息  头像
      const baseInfo = await getUserDetail(result.userId)
      const baseResult = { ...result, ...baseInfo }
      console.log(baseResult)
      commit('setUserInfo', baseResult)
      return baseResult
    },
    // 退出登录   移除token
    logout({ commit }) {
      commit('removeToken')
      commit('removeUserInfo')
      // 清空侧边栏菜单
      commit('setMenus', [])
      // 重置路路由规则
      resetRouter()
    }
  }
}
